package com.friend.joey.applicationfriend;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.icu.util.Calendar;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;


import com.friend.joey.applicationfriend.Database.MyDatabaseHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;


public class LoginActivity extends AppCompatActivity {

    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    //private MyDatabaseHelper dbHelper;//数据库
    private Button userlogin;
    private Button child;
    private Button trace;
    private Button userregister;
    private Button delete;
    private EditText username;
    private EditText userpass;
    private CheckBox rememberpass;
    private Calendar ctime;
    private boolean isRemember;
    private boolean isLogin;
    private boolean setTraceServer;
    private TraceService.TraceServiceBinder traceBinder;

    //
    private long time;
    //
    private MediaPlayer mediaPlayer=new MediaPlayer();
    //


    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            traceBinder=(TraceService.TraceServiceBinder)iBinder;
            traceBinder.setTraceServiceListener(new TraceService.TraceServiceListener() {
                @Override
                public void onBack(int state,int status, String s) {
                    //Toast.makeText(LoginActivity.this,s,Toast.LENGTH_LONG).show();
                    if(state==TraceService.GATHER_ON) {
                        //Toast.makeText(LoginActivity.this,"可以关闭",Toast.LENGTH_LONG).show();
                        startMainAcitivity();
                    }else if(state==TraceService.TRACE_OFF){
                        startMainAcitivity();
                    }
                }
            });

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //Toast.makeText(LoginActivity.this,"unBind",Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_login);
        pref= PreferenceManager.getDefaultSharedPreferences(this);
        //dbHelper = new MyDatabaseHelper(this,"TestTalk.db",null,1);//数据库
        isRemember = pref.getBoolean("remember_password",false);
        isLogin=pref.getBoolean("islogin",false);
        setTraceServer=pref.getBoolean("setTraceServer",false);


        Intent bindIntent = new Intent(LoginActivity.this,TraceService.class);
        bindService(bindIntent,connection,BIND_AUTO_CREATE);

        if(isLogin){
            setContentView(R.layout.activity_wait);
            onCreateLoginYES();
        }else {
            setContentView(R.layout.activity_login);
            onCreateLoginNO();
        }
    }

    private void onCreateLoginYES(){
        //startTraceServer();

        boolean ischild=pref.getBoolean("isChild",false);
        if(ischild){
            startChildMainActivity();
        }else{
            startMainAcitivity();
        }
    }
    private void onCreateLoginNO(){
        userlogin = (Button)findViewById(R.id.button_userlogin);
        userregister=(Button)findViewById(R.id.button_userregister);
        child = (Button)findViewById(R.id.button_child);
        trace = (Button)findViewById(R.id.button_trace);
        delete = (Button)findViewById(R.id.button_delete);
        username=(EditText)findViewById(R.id.text_username);
        userpass=(EditText)findViewById(R.id.text_userpassword);
        rememberpass=(CheckBox)findViewById(R.id.remeber_pass);

        if(isRemember){
            String name = pref.getString("name","");
            String password=pref.getString("password","");
            username.setText(name);
            userpass.setText(password);
            rememberpass.setChecked(true);
        }

        child.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //QueryMyDatabase();
//                if(ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
//                    ActivityCompat.requestPermissions(LoginActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
//                }else{
//                    initMediaPlayer();
//                }
                initFolder();

            }
        });
        trace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.TEST");
//                startActivity(intent);
//                finish();
//                NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//                Notification notification=new NotificationCompat.Builder(getApplicationContext())
//                        .setContentTitle("1")
//                        .setContentText("2")
//                        .setWhen(System.currentTimeMillis()+10000)
//                        .setSmallIcon(R.mipmap.ic_launcher)
//                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
//                        .setPriority(NotificationCompat.PRIORITY_MAX)
//                        .setDefaults(NotificationCompat.DEFAULT_ALL)
//                        .build();
//                notification.flags=Notification.FLAG_INSISTENT;
//                manager.notify(3,notification);
//                AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
//                int halfminute=3000;
//                long triggerAtTime= System.currentTimeMillis()+halfminute;
//                TimeDeal Mytime=new TimeDeal(TimeDeal.INITDATE);
//                time=triggerAtTime;
//                Intent i = new Intent(LoginActivity.this,AlarmService.class);
//                i.putExtra("time",(int)triggerAtTime);
//                i.putExtra("time2",(int)Mytime.GetTime()+halfminute);
//                PendingIntent pi= PendingIntent.getService(LoginActivity.this,(int)triggerAtTime,i,0);
//                manager.set(AlarmManager.RTC_WAKEUP,triggerAtTime,pi);
//                //Toast.makeText(LoginActivity.this,"测试定时",Toast.LENGTH_SHORT).show();
//                triggerAtTime=triggerAtTime+5000;
//                Intent t = new Intent(LoginActivity.this,AlarmService.class);
//                i.putExtra("time",(int)triggerAtTime);
//                i.putExtra("time2",(int)Mytime.GetTime()+halfminute+5000);
//                PendingIntent p= PendingIntent.getService(LoginActivity.this,(int)triggerAtTime,i,0);
//                manager.set(AlarmManager.RTC_WAKEUP,triggerAtTime,p);
                //InsertIntoMyDatabase();
                //DeleteFromeMyDatabase();
                //mediaPlayer.start();
                mediaPlayer.pause();
            }
        });


        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDatabaseHelper dbHelper;
                SQLiteDatabase db;
                dbHelper = new MyDatabaseHelper(LoginActivity.this,"TestTalk.db",null,2);
                db=dbHelper.getWritableDatabase();
                db.delete("message",null,null);

            }
        });
        userlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name=username.getText().toString();
                String password=userpass.getText().toString();
                if(name.equals("admin") && password.equals("1234")) {
                    editor=pref.edit();
                    if(rememberpass.isChecked()){
                        editor.putBoolean("remember_password",true);
                        editor.putString("name",name);
                        editor.putString("password",password);
                    }else{
                        editor.clear();
                    }
                    editor.putBoolean("islogin",true);
                    editor.putBoolean("isChild",false);
                    editor.commit();
                    startTraceServer();
                } else if(name.equals("admin2")){
//                    editor.putBoolean("islogin",true);
//                    editor.putBoolean("isChild",true);
                    Intent intent = new Intent();
                    intent.setAction("com.friend.joey.CHILD");
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(LoginActivity.this,"信息错误，请重新输入",Toast.LENGTH_SHORT).show();
                }
            }
        });
        userregister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                traceBinder.startGather(true);
                unbindService(connection);
            }
        });
    }
    private void initMediaPlayer(){
        try{
            File file=new File(Environment.getExternalStorageDirectory(),"music.mp3");
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
            Toast.makeText(LoginActivity.this, "准备", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Toast.makeText(LoginActivity.this, "失败", Toast.LENGTH_SHORT).show();
        }
    }
    public boolean readfile(String filepath) throws FileNotFoundException, IOException{
        try{
            File file = new  File(filepath);
//            File file=new File(Environment.getExternalStorageDirectory(),"MusicOldFriend");
//            String filepath=file.getPath();
            if(!file.isDirectory()){
                file.mkdir();
                Toast.makeText(LoginActivity.this, "不存在", Toast.LENGTH_SHORT).show();
            }else if(file.isDirectory()){
                String[] filelist=file.list();
                Toast.makeText(LoginActivity.this, "存在", Toast.LENGTH_SHORT).show();
                for(int i =0;i<filelist.length;i++){
                    File readfile=new File(filepath+"//"+filelist[i]);
                    if(!readfile.isDirectory()){
//                        System.out.println("path="+readfile.getPath());
//                        System.out.println("absolutepath="+readfile.getAbsolutePath());
//                        System.out.println("name="+readfile.getName());
                        if(readfile.exists()) {
                            String name = readfile.getName();
                            Toast.makeText(LoginActivity.this, readfile.getPath(), Toast.LENGTH_SHORT).show();
                            if (name.endsWith("mp3")) {
                                mediaPlayer.setDataSource(readfile.getPath());
                                mediaPlayer.prepare();
                                mediaPlayer.start();
                            }
                        }

                    }else if(readfile.isDirectory()){
                        readfile(filepath+"//"+filelist[i]);
                    }
                }
            }
        }catch(FileNotFoundException e){
            //Toast.makeText(LoginActivity.this, "异常", Toast.LENGTH_SHORT).show();
        }
        return true;
    }




    private void initFolder(){
        File file=new File(Environment.getExternalStorageDirectory(),"MusicOldFriend");
        boolean i=file.exists();
        boolean j=file.isDirectory();
        Toast.makeText(LoginActivity.this, "测试"+Boolean.toString(i)+Boolean.toString(j), Toast.LENGTH_SHORT).show();
        try {
            readfile(file.getPath());
        } catch (IOException e) {
            Toast.makeText(LoginActivity.this, "异常", Toast.LENGTH_SHORT).show();
        }
        //System.out.println(file.getAbsolutePath().toString());
    }

    public void InsertIntoMyDatabase(){
        Toast.makeText(LoginActivity.this, "添加", Toast.LENGTH_SHORT).show();
        MyDatabaseHelper dbHelper;
        SQLiteDatabase db;
        dbHelper = new MyDatabaseHelper(LoginActivity.this,"TestTalk.db",null,2);
        db=dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username","admin3");
        values.put("userpassword","1234");
        values.put("side",1);//0老人，1子女
        db.insert("user",null,values);
        db.close();
    }
    public void DeleteFromeMyDatabase(){
        Toast.makeText(LoginActivity.this, "删除", Toast.LENGTH_SHORT).show();
        MyDatabaseHelper dbHelper;
        SQLiteDatabase db;
        dbHelper = new MyDatabaseHelper(LoginActivity.this,"TestTalk.db",null,2);
        db=dbHelper.getWritableDatabase();
        db.delete("user","username=?",new String[]{"admin3"});
//        ContentValues values = new ContentValues();
//        values.put("username","admin3");
//        values.put("userpassword","1234");
//        //values.put("usersign","明天会更好");
//        values.put("side",1);//0老人，1子女
//        db.insert("user",null,values);
        db.close();
    }
    public void QueryMyDatabase(){
        Toast.makeText(LoginActivity.this, "查询", Toast.LENGTH_SHORT).show();
        MyDatabaseHelper dbHelper;
        SQLiteDatabase db;
        dbHelper = new MyDatabaseHelper(LoginActivity.this,"TestTalk.db",null,2);
        db=dbHelper.getWritableDatabase();
        Cursor cursor = db.query("user",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            while(cursor.moveToNext())
            {
                String text=cursor.getString(cursor.getColumnIndex("username"));
                Toast.makeText(LoginActivity.this,text,Toast.LENGTH_SHORT).show();
            }
        }
        else{
            Toast.makeText(LoginActivity.this, "数据库未获取到信息", Toast.LENGTH_SHORT).show();
        }
    }

    private void startMainAcitivity(){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.FRAGMENTS");
        startActivity(intent);
        finish();
    }
    private void startChildMainActivity(){
        Intent intent = new Intent();
        intent.setAction("com.friend.joey.CHILD");
        startActivity(intent);
        finish();
    }

    private void startTraceServer(){
        if(setTraceServer){
            //开启轨迹服务
                Intent startIntent = new Intent(LoginActivity.this, TraceService.class);
                startIntent.putExtra("entityName", "myTrace");
                startIntent.putExtra("gather", setTraceServer);
                startService(startIntent);
        }else{
            startMainAcitivity();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if(isLogin){
//            Toast.makeText(LoginActivity.this,"检测到已登陆，跳转中",Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent();
//            intent.setAction("android.intent.action.FRAGMENTS");
//            startActivity(intent);
//            finish();
//        }
    }

    @Override
    protected void onDestroy() {
        //Toast.makeText(LoginActivity.this,"关闭",Toast.LENGTH_LONG).show();
        unbindService(connection);
        super.onDestroy();
    }

}
